import {
    CanActivate,
    ExecutionContext,
    HttpException,
    HttpStatus,
    Injectable,
    UnauthorizedException,
  } from '@nestjs/common';
  import { JwtService } from '@nestjs/jwt';
  import { Request } from 'express';
  import { ConfigService } from '@nestjs/config';
  import { Reflector } from '@nestjs/core';
  
  @Injectable()
  
  export class IsAuthority implements CanActivate {
    constructor(
      private reflector: Reflector,
      private readonly jwtService: JwtService,
      private readonly configService: ConfigService,
    ) {}
    async canActivate(context: ExecutionContext): Promise<boolean> {
      
      const request: Request = context.switchToHttp().getRequest(); // 获取请求头
      const token = this.extractTokenFromHeader(request); // 获取请求中的token字段

      if (!token) {
        throw new UnauthorizedException('登录 token 错误，请重新登录');
      }
        try{
            const payload = await this.jwtService.verify(token, {
                secret: this.configService.get('JWT_SECRET'),
              });
              if(payload.user.role == 'admin'){
                return true;
           }else{
               console.log('---',payload.user)
               throw new HttpException('您不是管理员',HttpStatus.UNAUTHORIZED)
           }
        }catch{
            throw new HttpException('token错误',HttpStatus.UNAUTHORIZED)
        }

       
       
    }
  
    private extractTokenFromHeader(request: Request): string | undefined {
      const [type, token] = request.headers.authorization?.split(' ') ?? [];
      return type === 'Bearer' ? token : undefined;
    }
  }
  
  